import java.io.*;
import java.util.Collection;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class League {

    private Players playersHash;
    private PrintStream ps;
    private Map<String, Collection<Coach>> coaches;

    public League(Collection<Player> players, PrintStream ps, Map<String, Collection<Coach>> coaches) {
        this.playersHash = new Players(players);
        this.ps = ps;
        this.coaches = coaches;
    }

    public void listPlayerInfos() {
        Collection<Player> allPlayers = playersHash.getPlayersOlderThan(0);
        for (Player player: allPlayers){
            ps.println(player.getPlayerInfo());
        }
        for (Collection<Coach> coachList: coaches.values()){
            for (Coach coach: coachList){
                ps.println(coach.getInfo());
            }
        }
    }

    public void findPlayer(String name) {
        String playerInfo;
        Player player = playersHash.getPlayerByName(name);
        if (player!=null){
            playerInfo = player.getPlayerInfo();
        }
        else {
            playerInfo = "This player is not available";
        }
        ps.println(playerInfo);
    }

    public void listTeam(String name) {
        String teamInfo=null;
        Collection<Player> teamPlayers = playersHash.getPlayersByTeam(name);
        if (teamPlayers==null){
            teamInfo = "This team is not available \n";
        }
        else{
            for (Player player: teamPlayers){
               teamInfo+=player.getPlayerInfo()+"\n";
            }
            for (Coach coach: coaches.get(name)){
               teamInfo+=coach.getInfo()+"\n";
            }
        }
        ps.print(teamInfo);
    }

    public void tradePlayer(String player,String newTeam) {
        String tradeFeedback ="";
        Player traded = playersHash.getPlayerByName(player);
        if (traded==null){
            tradeFeedback = "The player you selected is not available. ";
        }
        String oldTeam = traded.getTeam();
        if (playersHash.getPlayersByTeam(newTeam)==null){
            tradeFeedback+="The team you want to trade to is not available";
        }
        if (tradeFeedback.equals("")){
            playersHash.tradePlayer(traded, newTeam);
            tradeFeedback = "The player "+player+" has been traded from "+oldTeam+" to "+newTeam;
        }
        ps.println(tradeFeedback);
    }
}
